package com.feiyuan.core.service.impl;

import com.feiyuan.common.exception.BusinessException;
import com.feiyuan.common.result.ResponseEnum;
import com.feiyuan.common.utils.MD5Utils;
import com.feiyuan.core.mapper.AdminUserMapper;
import com.feiyuan.core.mapper.AdminUserRoleMapper;
import com.feiyuan.core.pojo.entity.AdminUser;
import com.feiyuan.core.pojo.entity.AdminUserRole;
import com.feiyuan.core.service.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService {

    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private AdminUserRoleMapper adminUserRoleMapper;

    @Override
    public IPage<AdminUser> listPage(Integer pageNo, Integer pageSize, String userName, String name, String phone, String email) {
        Page<AdminUser> pageParam = new Page<>();
        return adminUserMapper.selectPage(pageParam, new QueryWrapper<AdminUser>().like(StringUtils.isNotEmpty(userName), "user_name", userName)
                .like(StringUtils.isNotEmpty(name), "name", name)
                .like(StringUtils.isNotEmpty(phone), "phone", phone)
                .like(StringUtils.isNotEmpty(email), "email", email));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateUser(AdminUser adminUser) {
        if (adminUser.getId() != null) {
            // 检查密码是否改变
            AdminUser user = adminUserMapper.selectById(adminUser.getId());
            if (!user.getPassword().equals(adminUser.getPassword())) {
                // 密码加密
                adminUser.setPassword(MD5Utils.getSaltMd5AndSha(adminUser.getPassword()));
            }
            if (adminUserMapper.updateById(adminUser) > 0) {
                List<AdminUserRole> userRole = adminUserRoleMapper.selectList(new QueryWrapper<AdminUserRole>().eq("user_id", adminUser.getId()));
                if (userRole != null && userRole.size() > 0) {
                    // 先删除，在添加
                    adminUserRoleMapper.delete(new QueryWrapper<AdminUserRole>().eq("user_id", adminUser.getId()));
                    this.saveUserRole(adminUser.getId(), adminUser.getRoleIds());
                } else {
                    // 保存用户与角色的关系
                    this.saveUserRole(adminUser.getId(), adminUser.getRoleIds());
                }
            }
        } else {
            List<AdminUser> userList = adminUserMapper.selectList(new QueryWrapper<AdminUser>().eq("user_name", adminUser.getUserName()));
            if (userList != null && userList.size() > 0) {
                throw new BusinessException(ResponseEnum.ADMIN_USERNAME_IS_NOT_REPEAT);
            }
            // 密码加密
            adminUser.setPassword(MD5Utils.getSaltMd5AndSha(adminUser.getPassword()));
            if (adminUserMapper.insert(adminUser) > 0) {
                // 保存用户与角色的关系
                this.saveUserRole(adminUser.getId(), adminUser.getRoleIds());
            }
        }
        return true;
    }

    @Override
    public Object getByUserId(Long id) {
        AdminUser adminUser = this.baseMapper.selectById(id);
        // 查询对应角色信息
        List<AdminUserRole> userRole = adminUserRoleMapper.selectList(new QueryWrapper<AdminUserRole>().eq("user_id", id));
        if (userRole != null && userRole.size() > 0) {
            List<Long> roleIds = new ArrayList<>();
            for (AdminUserRole adminUserRole : userRole) {
                roleIds.add(adminUserRole.getRoleId());
            }
            adminUser.setRoleIds(roleIds);
        }
        return adminUser;
    }

    /**
     * 保存用户与角色的关系
     * @param userId
     * @param roleIds
     */
    private void saveUserRole(Long userId, List<Long> roleIds) {
        if (roleIds != null && roleIds.size() > 0) {
            for (Long roleId : roleIds) {
                AdminUserRole adminUserRole = new AdminUserRole();
                adminUserRole.setUserId(userId);
                adminUserRole.setRoleId(roleId);
                adminUserRoleMapper.insert(adminUserRole);
            }
        }
    }
}
